import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
	baseURL: window.config.VUE_APP_BASE_API, // url = base url + request url
	withCredentials: true, // send cookies when cross-domain requests
	timeout: -1 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		if(store.getters.token) {
			config.headers['token'] = getToken();
			config.headers['Authorization'] = 'Bearer '+getToken();
		}
		return config
	},
	error => {
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	response => {
		const res = response.data
		if(res.code && res.code=="401"){
			MessageBox.alert('请登录后访问！', '登录', {
					confirmButtonText: '登录',
					type: 'warning'
				}).then(() => {
					store.dispatch('user/resetToken').then(() => {
						location.reload();
					})
				})
		}
		return res
	},
	error => {
		Message({
			message: '网络连接出错，请重试！',
			type: 'error',
			duration: 5 * 1000
		})
		return Promise.reject(error)
	}
)

export default service